//
//  CZComposeViewController.swift
//  iOSWeibo10
//
//  Created by itcast on 16/5/21.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

import SVProgressHUD

class CZComposeViewController: UIViewController {
    
    // 最大文字数
    private let statusMaxLength = 25
    
    private var isShowPhotoSelectorView = false

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = GlobalBKGColor
        
        setupNavigationBar()
        setupTextView()
        setupPhotoSelectorView()
        setupToolBar()
        setupLengthTipLabel()
        
        // 监听键盘frame将要改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        // 主动弹出键盘
//        self.textView.becomeFirstResponder()
    }
    
    // view已经显示出来,将键盘弹出来
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        // 照片选择器的view没有出来才需要主动弹出键盘
        if !isShowPhotoSelectorView {
            // 主动弹出键盘
            self.textView.becomeFirstResponder()
        }
    }
    
    // 移除
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    /*
    // 键盘弹出
    userInfo = {
        UIKeyboardAnimationCurveUserInfoKey = 7;
        UIKeyboardAnimationDurationUserInfoKey = "0.25";    // 动画时间
        UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
        UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
        UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
        UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}"; // 开始位置
        UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";   // 键盘最终位置   216
        UIKeyboardIsLocalUserInfoKey = 1;
    }
    */
    
    /// 键盘改变的方法
    func willChangeFrame(notification: NSNotification) {
        CZPrint(items: "notification: \(notification)")
        
        // 获取键盘动画的时间
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        // 获取最终的frame值
        let frame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        // 计算toolBar底部的间距
        let bottomMargin = -(UIScreen.mainScreen().bounds.height - frame.origin.y)
        
        UIView.animateWithDuration(duration) { () -> Void in
            // 更新约束
            self.toolBar.snp_updateConstraints { (make) -> Void in
                make.bottom.equalTo(self.view).offset(bottomMargin)
            }
            
            self.view.layoutIfNeeded()
        }
    }
    
    // 设置照片选择器的view
    private func setupPhotoSelectorView() {
        let photoSelectorView = photoSelectorVC.view
        
        // 添加到self.view
        self.view.addSubview(photoSelectorView)
        
        // 当一个控制器的view成为另一个控制器的view的子view时,这个控制器需要成为另一个控制器的子控制器
        self.addChildViewController(photoSelectorVC)
        
        // 添加约束
        photoSelectorView.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.equalTo(self.view)
            let height = UIScreen.mainScreen().bounds.height * 0.6
            make.height.equalTo(height)
            
            make.bottom.equalTo(self.view).offset(height)
        }
    }
    
    private func setupLengthTipLabel() {
        self.view.addSubview(lengthTipLabel)
        
        lengthTipLabel.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(self.view).offset(-3)
            make.bottom.equalTo(toolBar.snp_top).offset(-3)
        }
    }
    
    /// 设置toolBar
    private func setupToolBar() {
        // 1.添加控件
        self.view.addSubview(toolBar)
        
        // 2.添加约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(self.view)
            make.height.equalTo(44)
        }
        
        // 添加内容item
        // 每个item对应的图片名称
        let itemSettings = [
            ["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_keyboardbutton_background", "action": "emoticon:"],
            ["imageName": "compose_add_background", "action": "add"]
        ]
        // 创建空数组
        var index = 0
        toolBar.items = [UIBarButtonItem]()
        for dict in itemSettings {
            // 获取图片名称
            let imageName = dict["imageName"]!
            // 获取图片对应的点击事件
            let action = dict["action"]!
            
            // 创建 UIBarButtonItem
            // Selector: 可以直接给字符串,但是不能给字符串变量和常量
            let item = UIBarButtonItem(imageName: imageName, target: self, action: Selector(action))
            
            // 给item里面的按钮设置tag
            item.customView?.tag = index
            // 出不来toolBar.items没有人给他创建值
            toolBar.items?.append(item)
            
            // 创建弹簧
            toolBar.items?.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: ""))
            index++
        }
        
        // 添加完item后删除最后多的一根弹簧
        toolBar.items?.removeLast()
    }
    
    // MARK: - 按钮点击事件
    @objc private func itemDidClick(button: UIButton) {
        switch button.tag {
        case 0:
            CZPrint(items: "点击了图片")
        case 1:
            CZPrint(items: "点击了#")
        case 2:
            CZPrint(items: "点击了@")
        case 3:
            CZPrint(items: "点击了表情")
        case 4:
            CZPrint(items: "点击了+")
        default:
            CZPrint(items: "你点击了一个不存在的按钮")
        }
    }
    
    @objc private func picture() {
        // 照片选择器的view要上来
        UIView.animateWithDuration(CZDefaultDuration) { () -> Void in
            self.photoSelectorVC.view.snp_updateConstraints { (make) -> Void in
                make.bottom.equalTo(self.view)
            }
            
            self.view.layoutIfNeeded()
        }
        
        textView.resignFirstResponder()
        
        isShowPhotoSelectorView = true
    }
    
    @objc private func trend() {
        CZPrint(items: "trend")
    }
    
    @objc private func mention() {
        CZPrint(items: "mention")
    }
    
    @objc private func emoticon(button: UIButton) {
        CZPrint(items: "emoticon")
        // 设置表情键盘
        
        // compose_emoticonbutton_background_highlighted
        var image: UIImage?
        var selectedImage: UIImage?
        // 在弹出前, inputView == nil,就弹出系统键盘, inputView != nil, 就使用设置的键盘
        if textView.inputView == nil {
            textView.inputView = emoticonKeyboardView
            
            image = UIImage(named: "compose_emoticonbutton_background")
            selectedImage = UIImage(named: "compose_emoticonbutton_background_highlighted")
        } else {
            textView.inputView = nil
            
            image = UIImage(named: "compose_keyboardbutton_background")
            selectedImage = UIImage(named: "compose_keyboardbutton_background_highlighted")
        }
        
        button.setImage(image, forState: UIControlState.Normal)
        button.setImage(selectedImage, forState: UIControlState.Highlighted)
        
        // 先退回再出来
        textView.resignFirstResponder()
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            self.textView.becomeFirstResponder()
        }
    }
    
    @objc private func add() {
        CZPrint(items: "add")
    }
    
    private func setupTextView() {
        // 1.添加控件
        self.view.addSubview(textView)
        
        // 2.添加约束
        // 填充父控件
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view)
        }
    }
    
    /**
     设置导航栏
     */
    private func setupNavigationBar() {
        // 左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        // 右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        // 按钮不可用
        navigationItem.rightBarButtonItem?.enabled = false
        
        setupTitleView()
    }
    
    /// 设置导航栏的标题
    private func setupTitleView() {
        let prefix = "发微博"
        if let name = CZUserAccountViewModel.sharedInstance.userAccount?.screen_name {
            // \n 换行符
            let text = prefix + "\n" + name
            // 获取到用户名称
            let label = UILabel()
            label.textColor = UIColor.blackColor()
            label.font = UIFont.systemFontOfSize(13)
            label.numberOfLines = 0
            label.textAlignment = NSTextAlignment.Center
            
            // 创建属性文本
            let attrText = NSMutableAttributedString(string: text)
            
            // 获取用户名称的范围
            let nameRange = (text as NSString).rangeOfString(name)
            
            // 属性文本添加属性
            attrText.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: nameRange)
            attrText.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(11), range: nameRange)
            
            label.attributedText = attrText
            // 注意设置sizeToFit需要在label有内容后才可以
            label.sizeToFit()
            
            navigationItem.titleView = label
            
        } else {
            // 没有用户名称
            navigationItem.title = prefix
        }
    }
    
    /// 发布微博
    @objc private func sendStatus() {
        let text = textView.emoticonNameText()
        
        // 判断是否超出
        if statusMaxLength - text.characters.count < 0 {
            SVProgressHUD.showErrorWithStatus("超出长度")
            return
        }
        
        // 提示正在发布微博
        SVProgressHUD.showWithStatus("正在发布微博...")
        
        let image = photoSelectorVC.photos.first
        
        // 发微博
        CZStatusViewModel.sharedInstance.sendStatus(image, statusString: text) { (error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发布微博失败")
                return
            }
            
            // 成功了
            SVProgressHUD.showSuccessWithStatus("发布微博成功了")
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                self.close()
            })
        }
    }
    
    /// 关闭控制器
    @objc private func close() {
        // 关闭控制器
        self.dismissViewControllerAnimated(true, completion: nil)
        
        // 关闭键盘
        self.textView.resignFirstResponder()
    }
    
    /*
        iOS中让用户输入的控件
            1.UITextField
                1.只能显示一行
                2.不能滚动
                3.有占位文本
    
    
            2.UITextView
                1.可以显示多行
                2.可以滚动
                3.没有占位文本
    */
    // MARK: - 懒加载
    /// textView
    private lazy var textView: CZPlaceholderTextView = {
        let tv = CZPlaceholderTextView()
        
        // 设置
//        tv.backgroundColor = UIColor.brownColor()
        tv.font = UIFont.systemFontOfSize(ComposeTextFontSize)
        
        // 设置占位文本
        tv.placeholder = "请输入.."
        
        // 设置控制器成为代理监听textView文本改变
        tv.delegate = self
        
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        tv.alwaysBounceVertical = true

        return tv
    }()
    
    /// toolBar
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    /// 键盘View
    private lazy var emoticonKeyboardView: CZEmoticonKeyboard = {
        let keyboard = CZEmoticonKeyboard()
        
        // 设置textView
        keyboard.textView = self.textView
        
        return keyboard
    }()
    
    /// 长度提示label
    private lazy var lengthTipLabel: UILabel = {
        let label = UILabel()
        
        // 设置
        label.textColor = UIColor.lightGrayColor()
        label.font = UIFont.systemFontOfSize(10)
        label.text = String(self.statusMaxLength)
        label.sizeToFit()
        
        return label
    }()
    
    /// 照片选择控制器
    private lazy var photoSelectorVC: CZPhotoSelectorController = CZPhotoSelectorController()
}

extension CZComposeViewController: UITextViewDelegate {
    // 文字改变
    func textViewDidChange(textView: UITextView) {
        CZPrint(items: "文字改变: \(textView.text)")
        
        // 有文字,rightBarButtonItem可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        // 获取textView文字长度
        let length = textView.emoticonNameText().characters.count
        
        let leftLength = statusMaxLength - length
        lengthTipLabel.text = String(leftLength)
        
        lengthTipLabel.textColor = leftLength < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
    }
}
